<template>
  <div class="edit-index">
    <div class="edit-main">
      <el-select
        :disabled="this.urlToken ? true : false"
        class="edit-select"
        v-model="queryInfo.semesterId"
        placeholder="请选择"
        @change="onGetSchedule"
      >
        <el-option
          v-for="item in semesterList"
          :key="item.id"
          :label="item.semesterName"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-select
        class="edit-select"
        v-model="queryInfo.weekNum"
        placeholder="请选择"
        @change="onGetSchedule"
      >
        <el-option
          v-for="item in weekTotalList"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-select
        class="edit-select"
        v-model="batchType"
        placeholder="请选择"
        @change="onGetBatchType"
      >
        <el-option label="第一批次" value="1" />
        <el-option label="第二批次" value="2" />
      </el-select>

      <el-row>
        <el-col :span="3" v-for="(item, index) in weekHeaderRow" :key="index"
          ><el-card class="week-bgc"
            ><div>
              <span>{{ item.weekDescription }}</span>
              <span v-if="item.weekDate">{{
                item.weekDate | formatTime("YYYY-MM-DD")
              }}</span>
              <span v-else>{{ item.weekDate }}</span>
            </div></el-card
          ></el-col
        >
      </el-row>
      <el-row v-for="(item, index) in sectionList" :key="index">
        <el-col :span="3"
          ><el-card class="section-bgc">
            <div>
              <span>{{ item.sectionName }}</span>
              <span>{{ item.sectionTime }}</span>
            </div></el-card
          ></el-col
        >
        <el-col
          :span="3"
          v-for="(item2, index2) in rowList[index]"
          :key="index2"
        >
          <el-popover
            placement="right-end"
            trigger="hover"
            itle="文章详情"
            :open-delay="200"
            :close-delay="0"
          >
            课程名称：{{ item2.courseName }}<br />
            实验名称：{{ item2.experimentName }}<br />
            课程班级：{{ item2.className }}<br />
            老师工号：{{ item2.teacherId }}<br />
            授课老师：{{ item2.teacherName }}<br />

            <el-card
              style="font-size: 14px"
              slot="reference"
              @click.native="isShow(item2)"
              :class="item2.courseName ? 'course-bgc' : ''"
            >
              <i
                v-show="item2.courseName && isAdmin"
                class="el-icon-close delete-icon"
                @click="deleteCourse(item2.id)"
              ></i>
              <div>
                <span>{{ item2.courseName ? item2.courseName : "---" }}</span>
                <span>{{
                  item2.experimentName ? item2.experimentName : "---"
                }}</span>
                <span>{{ item2.teacherName ? item2.teacherName : "---" }}</span>
              </div></el-card
            ></el-popover
          >
        </el-col>
      </el-row>
    </div>
    <el-dialog
      title="课程详情"
      :visible.sync="dialogFormVisible"
      append-to-body
      destroy-on-close
      @close="resetForm"
      class="dialogRef"
    >
      <el-form :rules="editRules" :model="form" ref="editFormRef">
        <el-form-item
          prop="courseName"
          label="课程名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.courseName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="experimentName"
          label="实验名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.experimentName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="班级名称" :label-width="formLabelWidth">
          <el-cascader
            v-model="selectClass"
            :options="options"
            :props="props"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          prop="teacherId"
          label="老师工号"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.teacherId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="teacherName"
          label="授课老师"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.teacherName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editContent">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSectionByBatchType } from "@/api/adminSectionTime";
import { getSemester, getSemesterById } from "@/api/adminEditSemester";
import { getClassList } from "@/api/adminEditClass";
import {
  addCourse,
  editCourse,
  deleteCourse,
  getSchedule,
  getCourseById,
} from "@/api/adminEditCourse";
import { getMajor } from "@/api/adminEditMajor";

import { apiGetSectionByBatchType } from "@/api/apiSectionTime";
import { apiGetSemester, apiGetSemesterById } from "@/api/apiEditSemester";
import { apiGetClassList } from "@/api/apiEditClass";
import { apiAddCourse, apiGetSchedule } from "@/api/apiEditCourse";
import { isConfirm } from "@/utils/confirm";
export default {
  // 组件名称
  name: "editIndex",
  // 组件参数 接收来自父组件的数据
  props: {},
  // 局部注册的组件
  components: {},
  // 组件状态值
  data() {
    return {
      isAdmin: false, //判断是不是admin接口
      urlToken: "", //地址栏携带的token
      semesterOriginDate: "", //学期第一周的第一天日期
      weekTotalList: [],
      semesterList: [],
      queryInfo: {
        weekNum: "",
        semesterId: "",
      },
      batchType: "1",
      weekHeaderRow: {}, //周一到周日日期
      rowList: [],
      sectionList: [], //节次时间
      dialogFormVisible: false, //表单的显示与隐藏
      //表单信息
      form: {
        semesterId: "", //学期Id
        teacherId: "",
        teacherName: "",
        courseName: "",
        className: "",
        experimentName: "",
        weekNum: "",
        week: "",
      },
      editRules: {
        teacherId: [
          { required: true, message: "请输入教师工号", trigger: "blur" },
        ],
        teacherName: [
          { required: true, message: "请输入教师姓名", trigger: "blur" },
        ],
        courseName: [
          { required: true, message: "请输入课程名称", trigger: "blur" },
        ],
        selectClass: [
          { required: true, message: "请输入班级名称", trigger: "blur" },
        ],
        experimentName: [
          { required: true, message: "请输入实验名称", trigger: "blur" },
        ],
      },
      editCourseId: "", //修改的Id
      formLabelWidth: "120px", //表单宽度
      options: [], //级联选择器的绑定数组
      props: { expandTrigger: "hover", multiple: true, emitPath: false }, //级联选择器多选配置
      classList: [], //级联选择器上的所有班级
      majorList: [], //级联选择器上的所有专业
      selectClass: [], //选中的班级id
      selectClassName: [], //选中的班级名字
      isDelete: false, //是否删除操作
      arr: [],
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  created() {
    if (window.localStorage.USER_KEY) {
      this.isAdmin = true;
    }
    const splits = window.location.pathname.split("/");
    this.urlToken = splits[splits.length - 1];
    this.onGetSemester();
  },
  mounted() {},
  // 组件方法
  methods: {
    //获取学期数据
    async onGetSemester() {
      let data;
      if (this.isAdmin) {
        data = await getSemester();
      } else {
        data = await apiGetSemester(this.urlToken);
      }
      this.semesterList = data.data.data.items; //拿到所有学期信息
      const timestamp = new Date().getTime(); //当前日期的时间戳
      let date;
      let i;
      //拿到当前主学期
      for (i = 0; i < this.semesterList.length; i++) {
        //判断哪个是当前主学期
        if (this.semesterList[i].isCurrentSemester) {
          date = new Date(
            Date.parse(
              this.semesterList[i].semesterOriginDate.replace(/-/g, "/")
            )
          );
          date = date.getTime();
          break;
        }
      }
      const time = timestamp - date; //拿到今天距离主学期第一天的时间戳
      this.queryInfo.semesterId = this.semesterList[i].id;
      //计算当天为第几周
      this.queryInfo.weekNum = String(Math.ceil(time / 86400000 / 7));
      if (
        this.queryInfo.weekNum <= this.semesterList[i].semesterWeekTotal &&
        this.queryInfo.weekNum > 0
      ) {
        this.queryInfo.weekNum = this.queryInfo.weekNum;
      } else {
        this.queryInfo.weekNum = 1;
      }
      this.init();
    },
    init() {
      this.handleWeekTotalList();
      this.onGetSchedule();
      this.onGetBatchType();
      this.onGetClassList();
      this.onGetMajor();
    },
    //根据学生批次获取节次时间
    async onGetBatchType() {
      let data;
      if (this.isAdmin) {
        data = await getSectionByBatchType(Number(this.batchType));
      } else {
        data = await apiGetSectionByBatchType(
          Number(this.batchType),
          this.urlToken
        );
      }
      this.sectionList = data.data.data.items;
    },
    //获取每周数据
    async onGetSchedule() {
      //根据Id获取选中学期的数据
      let res;
      if (this.isAdmin) {
        res = await getSemesterById(this.queryInfo.semesterId);
      } else {
        res = await apiGetSemesterById(
          this.queryInfo.semesterId,
          this.urlToken
        );
      }

      //判断切换学期的最大周数是否大于当前学期的选中周数
      const {
        data: {
          data: { item },
        },
      } = res;
      if (this.queryInfo.weekNum > item.semesterWeekTotal) {
        this.queryInfo.weekNum = String(item.semesterWeekTotal);
      } else {
        this.queryInfo.weekNum = String(this.queryInfo.weekNum);
      }
      let data;
      if (this.isAdmin) {
        data = await getSchedule(this.queryInfo);
      } else {
        data = await apiGetSchedule(this.queryInfo, this.urlToken);
      }
      this.rowList = data.data.data.schedule.rowLists;
      data.data.data.schedule.rowLists;
      this.weekHeaderRow = data.data.data.schedule.weekHeaderRow;
      this.handleWeekTotalList();
    },
    //处理总周数
    handleWeekTotalList() {
      this.weekTotalList = [];
      this.semesterList.forEach((item) => {
        if (item.id == this.queryInfo.semesterId) {
          for (let i = 1; i <= item.semesterWeekTotal; i++) {
            let obj = {
              name: "第" + i + "周",
              value: i + "",
            };
            this.weekTotalList.push(obj);
          }
        }
      });
    },
    //点击卡片显示弹出框，回显
    async isShow(item) {
      this.relationClassAndMajor();
      if (!window.localStorage.USER_KEY && item.id) return;
      if (this.isDelete) return;
      this.arr = [];
      this.selectClass = [];
      this.selectClassName = [];
      if (item.id) {
        const { data } = await getCourseById(item.id);
        this.form = data.data.schedule;
        this.arr = this.form.className.split(",");
        this.arr.forEach((item) => {
          this.classList.forEach((item2) => {
            if (item2.className == item) {
              this.selectClass.push(item2.id);
            }
          });
        });
        this.editCourseId = item.id;
      } else {
        this.form = item;
        this.editCourseId = "";
      }
      this.dialogFormVisible = true;
      // this.form.weekNum = Number(this.queryInfo.weekNum);
    },
    //获取所有班级
    async onGetClassList() {
      let data;
      if (this.isAdmin) {
        data = await getClassList();
      } else {
        data = await apiGetClassList(this.urlToken);
      }
      this.classList = data.data.data.items;
    },
    //获取所有专业
    async onGetMajor() {
      const { data } = await getMajor();
      this.majorList = data.data.items;
    },
    //关联班级和专业
    relationClassAndMajor() {
      this.options = [];
      this.majorList.forEach((item) => {
        let oneObj = {};
        let children = [];
        let twoObj = {};
        oneObj = {
          value: item.sort,
          label: item.majorName,
        };
        this.classList.forEach((item2) => {
          if (item2.majorName == oneObj.label) {
            twoObj = {
              value: item2.id,
              label: item2.className,
            };
            children.push(twoObj);
          }
        });
        oneObj.children = children;
        this.options.push(oneObj);
      });
    },
    //点击确定添加/修改课程
    editContent() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          this.selectClass.forEach((item) => {
            this.classList.forEach((item2) => {
              if (item2.id == item) {
                this.selectClassName.push(item2.className);
              }
            });
          });
          // [{id: 1, text: 1}]
          // [1, 2]
          // const obj = {};
          // this.classList.forEach((item2) => {
          //   obj[item2.id] = item2;
          // });
          // this.selectClass.forEach((item) => {
          //   obj[item] && this.selectClassName.push(obj[item].className);
          // })
          this.form.className = this.selectClassName + "";
          if (this.editCourseId) {
            await editCourse(this.form);
            //关闭弹出框
            this.dialogFormVisible = false;
          } else {
            if (await isConfirm("添加后将无法修改, 是否添加?")) {
              //提交添加的课程
              if (this.isAdmin) {
                addCourse(this.form);
              } else {
                apiAddCourse(this.form, this.urlToken);
              }
              //关闭弹出框
              this.dialogFormVisible = false;
            }
          }
          this.onGetSchedule();
        }
      });
    },
    //点击 × ，删除课程
    async deleteCourse(id) {
      if (!window.localStorage.USER_KEY) return;
      this.isDelete = true;
      if (await isConfirm("操作将删除该课程, 是否继续?")) {
        await deleteCourse(id);
        this.onGetSchedule();
        this.isDelete = false;
      }
    },
    //关闭对话框Dialog 重置表单
    resetForm() {
      //重置表单
      this.form.teacherId = "";
      this.form.teacherName = "";
      this.form.courseName = "";
      this.form.experimentName = "";
      this.form.className = "";
      this.form.id = "";
      this.selectClass = [];
      this.selectClassName = [];
      //关闭对话框
      this.dialogFormVisible = false;
    },
  },
};
</script> 

<style scoped lang='less'>
.edit-index {
  .edit-main {
    .edit-select {
      margin-bottom: 20px;
    }
    /deep/ .el-row {
      .el-col {
        .section-bgc {
          background-color: skyblue;
        }
        .week-bgc {
          background-color: #eee;
        }
        .course-bgc {
          background-color: rgb(252, 144, 144);
        }
        .el-card {
          position: relative;
          .delete-icon {
            cursor: pointer;
            position: absolute;
            top: 5px;
            right: 5px;
            z-index: 999;
          }
          .el-card__body {
            display: table;
            margin: 0 auto;
            height: 93px;
            padding: 5px;
            div {
              display: table-cell;
              vertical-align: middle;
              text-align: center;
              span {
                display: block;
              }
            }
          }
        }
      }
    }
  }
}
</style>
